package com.jt.ktdemo.ui.login

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Bundle
import android.text.Editable
import android.text.InputType
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.LifecycleOwner
import com.jt.ktdemo.ui.mian.MainActivity
import com.jt.ktdemo.R
import com.jt.ktdemo.bean.LoginCallbackBean
import com.jt.ktdemo.databinding.ActivityLoginBinding
import com.jt.ktdemo.http.HTTPAPI
import com.jt.ktdemo.ui.MyObservabler
import com.jt.ktdemo.ui.changePwd.ChangePwdActivity
import com.jt.ktdemo.ui.register.RegisterActivity
import com.jt.ktdemo.utils.GsonUtils
import com.jt.ktdemo.utils.LogUtil
import com.jt.ktdemo.utils.SpUtils
import com.lzy.okgo.callback.StringCallback
import okhttp3.Call
import okhttp3.Response

class LoginActivity : AppCompatActivity() {

    private lateinit var binding: ActivityLoginBinding
    private var firstEditText: Boolean = false
    private var secondEditText: Boolean = false
    private var pwdPoint: Boolean = true
    val sampleDrawables = intArrayOf(R.drawable.yanjing_xianshi_o, R.drawable.yanjing_yincang_o)


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityLoginBinding.inflate(layoutInflater)
        setContentView(binding.root)

        var session: String = SpUtils["module_session", ""].toString()
        if (!session.isEmpty()) {
            startActivity(Intent(this@LoginActivity, MainActivity().javaClass))
            finish()
        }

        //添加生命监室
        lifecycle.addObserver(MyObservabler())

        binding.tvModuleRegister.setOnClickListener {
            startActivity(Intent(this, RegisterActivity().javaClass))
            finish()
        }


        var llModule: LinearLayout = findViewById(R.id.llModulePro)
        binding.btModuleLogin.setOnClickListener {
            if (firstEditText && secondEditText) {
                var name: String = binding.username.getText().toString().trim()
                var pwd: String = binding.password.getText().toString().trim()
                if (TextUtils.isEmpty(name)) {
                    showToast("Please enter your name")
                } else if (TextUtils.isEmpty(pwd)) {
                    showToast("please enter your PIN")
                } else {
                    toLogin(name, pwd, llModule)
                }
            }
        }

        var ivModulePwd = findViewById<ImageView>(R.id.ivModulePwd)
        ivModulePwd.setOnClickListener {
            if (pwdPoint) {
                pwdPoint = false
                ivModulePwd.setImageResource(sampleDrawables[0])
                binding.password.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
            } else {
                pwdPoint = true
                ivModulePwd.setImageResource(sampleDrawables[1])
                binding.password.setInputType(InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD)
            }
            binding.password.setSelection(binding.password.text.toString().length)
        }
        binding.textView2.setOnClickListener{
            startActivity(Intent(this@LoginActivity, ChangePwdActivity().javaClass))
        }

        binding.username.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }

            override fun afterTextChanged(s: Editable?) {
                var inputStr = s.toString();
                firstEditText = !TextUtils.isEmpty(inputStr)
                checkBoolean()
            }
        })

        binding.password.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }

            override fun afterTextChanged(s: Editable?) {
                var inputStr = s.toString();
                secondEditText = !TextUtils.isEmpty(inputStr)
                checkBoolean()
            }
        })
    }

    /**
     * 显示弹窗
     */
    fun showToast(msg: String) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
    }

    fun toLogin(email: String, pwd: String, llModule: LinearLayout) {
        HTTPAPI.toLogin(email, pwd, object : StringCallback() {
            override fun onSuccess(t: String?, call: Call?, response: Response?) {
                llModule.visibility = View.GONE
                LogUtil.e("登录结果$t")
                var bean: LoginCallbackBean =
                    GsonUtils.parse(t.toString(), LoginCallbackBean::class.java)
                if (!bean.IsError) {
                    if (!TextUtils.isEmpty(bean.session)) {

                    }
                    if(!TextUtils.isEmpty(bean.session)){
                        SpUtils.put("module_session", bean.session)
                    }
                    SpUtils.put("module_uid", bean.uid)
                    SpUtils.put("module_nickName",bean.username)
                    startActivity(Intent(this@LoginActivity, MainActivity().javaClass))
                } else {
                    Toast.makeText(this@LoginActivity, bean.ErrorMessage, Toast.LENGTH_SHORT).show()
                }
            }

            override fun onError(call: Call?, response: Response?, e: Exception?) {
                llModule.visibility = View.GONE
                LogUtil.e("登录失败 ${GsonUtils.to(e)}")
                Toast.makeText(this@LoginActivity,"登录失败-->"+ GsonUtils.to(e),Toast.LENGTH_SHORT).show()
            }
        })
    }

    @SuppressLint("NewApi")
    fun checkBoolean() {
        if (firstEditText && secondEditText) {
            binding.btModuleLogin.setBackgroundResource(R.drawable.draw_module_login_bg)
        } else {
            binding.btModuleLogin.setBackgroundResource(R.drawable.draw_module_login_bg_selected)
        }
    }
}